package util

import (
	"crypto/md5"
	"encoding/hex"
	idworker "github.com/gitstliu/go-id-worker"
	"io/ioutil"
	"net/http"
	"regexp"
	"strconv"
	"strings"
	"time"
)

const (
	Salt = "2d1c7c980dd68062049ab93f82ba7897"
)

func NewId() string {
	currWoker := &idworker.IdWorker{}
	currWoker.InitIdWorker(10, 2)
	newId, _ := currWoker.NextId()
	id := strconv.FormatInt(newId, 32)
	return id
}

//  加密
func Encryption(value string) string {
	h := md5.New()
	h.Write([]byte(value + Salt))
	return hex.EncodeToString(h.Sum(nil))
}
//
func HttpRequest(url string) (b []byte, res http.Header, er error) {
	req, err := http.NewRequest("GET", url, nil)
	if err != nil {
		return nil, nil, err
	}
	req.Header.Add("User-Agent", "Mozilla/5.0 (Linux; Android 8.0.0; Pixel 2 XL Build/OPD1.170816.004) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.25 Mobile Safari/537.36")
	req.Header.Add("Accept", "*/*")
	req.Header.Add("Referer", "https://share.izuiyou.com/api/post/detail")
	req.Header.Add("Accept-Language", "zh-CN,zh;q=0.8,en-US;q=0.5,en;q=0.3")
	req.Header.Add("Connection", "keep-alive")
	client := http.Client{
		CheckRedirect: func(req *http.Request, via []*http.Request) error {
			return http.ErrUseLastResponse
		},
		Timeout: 30 * time.Second,
	}
	resp, err := client.Do(req)
	if err != nil {
		return nil, nil, err
	}
	defer resp.Body.Close()
	body, _ := ioutil.ReadAll(resp.Body)
	header := resp.Header
	return body, header, nil

}
func GetItemId(res string, str string) string  {
	//r := regexp.MustCompile(`video/([0-9]+)/`)
	r := regexp.MustCompile(res)
	result1 := r.FindStringSubmatch(str)
	if len(result1) >0  {
		v := strings.Split(result1[0], "/")
		return v[1]
	}
	return  ""
}